package cn.liziguo;

import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


/**
 * 主窗口
 *
 * @author Liziguo
 * @date 2025-04-08
 */
public class WinMain extends JFrame {

    /**
     * 屏幕分辨率
     */
    public final static int SCREEN_WIDTH;
    /**
     * 屏幕分辨率
     */
    public final static int SCREEN_HEIGHT;

    static {
        // 获取屏幕分辨率
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        SCREEN_WIDTH = screenSize.width;
        SCREEN_HEIGHT = screenSize.height;
    }

    public WinMain(MyPanel panel) {
        // 不显示在Alt+Tab里
        setType(JFrame.Type.UTILITY);
        // 防止按Alt+F4关闭
        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        // 位置
        setLocation(0, 0);
        // 大小,大小为屏幕分辨率
        setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        // 设置为未修饰的 隐藏最大化最小化和边框
        setUndecorated(true);
        // 窗口始终在最顶上
        setAlwaysOnTop(true);
        // 设置窗口为透明色
        setBackground(new Color(0, 0, 0, 0));
        // 添加画布
        add(panel);
        // 设置窗口为透明色
        setVisible(true);
        // 开启窗口虚化
        setWindowKamui();
    }

    /**
     * 点击窗口时会穿透窗口(无法被点击 不然鼠标不小心点到雪花焦点就会转移到这个窗口上)
     */
    public void setWindowKamui() {
        setTitle(UUID.randomUUID().toString());
        // 获取窗口句柄
        WinDef.HWND hwnd = User32.INSTANCE.FindWindow("SunAwtFrame", getTitle());
        // 设置扩展样式：透明且不拦截点击
        int exStyle = User32.INSTANCE.GetWindowLong(hwnd, WinUser.GWL_EXSTYLE);
        exStyle |= WinUser.WS_EX_LAYERED | WinUser.WS_EX_TRANSPARENT;
        User32.INSTANCE.SetWindowLong(hwnd, WinUser.GWL_EXSTYLE, exStyle);
        setTitle("");
    }

    public static void main(String[] args) {
        BufferedImage image;
        try {
            // 加载雪花图片
            image = ImageIO.read(new File("snowflake.png"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // fps = 150, snowflakeAdd = 3 (越小雪花越多)
        MyPanel myPanel = new MyPanel(image, 150, 3);
        new WinMain(myPanel);
    }
}